#pragma once
#include<vector>
#include<pthread.h>
#include<string>
#include<queue>

#define Default 3

class PthreadData{
public:
    std::string name_;
    pthread_t tid_;
};

template<class T>
class Threadpool{
public:
    void lock()
    {
        pthread_mutex_lock(&mutex_);
    }

    void unlock()
    {
        pthread_mutex_unlock(&mutex_);
    }

    bool empty()
    {
        return rq_.empty();
    }

    int wait()
    {
        return pthread_cond_wait(&cond_,&mutex_);
    }

    void wakeup()
    {
        pthread_cond_signal(&cond_);
    }

    std::string getName(pthread_t tid)
    {
        for(auto& e:tds_)
        {
            if(e.tid_==tid)
            {
                return e.name_;
            }
        }

        return "None";
    } 

public:
    Threadpool(int num=Default):tds_(num)
    {
        pthread_mutex_init(&mutex_,nullptr);
        pthread_cond_init(&cond_,nullptr);
    }

    static void* Handlertask(void* args)
    {    
        Threadpool<T>* tp=static_cast<Threadpool<T>*> (args);
        std::string name=tp->getName(pthread_self());
        while(1)
        {   
            tp->lock();
            while(tp->empty())
            {//循环判断防止伪唤醒
                tp->wait();
            }
            T t=tp->pop();
            tp->unlock();

            t();
            std::cout<<name<<":";
            t.getResult();
        }

        return nullptr;
    }

    void start()
    {
        for(int i=0;i<tds_.size();i++)
        {
            pthread_t td;
            pthread_create(&td,nullptr,Handlertask,this);
            tds_[i].tid_=td;
            tds_[i].name_="thread-"+std::to_string(i);
        }
    }
    
    void push(T t)
    {
        rq_.push(t);
        wakeup();
    }

    T pop()
    {
        T t=rq_.front();
        rq_.pop();
        return t;
    }

    ~Threadpool()
    {
        for(int i=0;i<tds_.size();i++)
        {
            pthread_join(&(tds_[i].tid_),nullptr);
        }
        pthread_mutex_destroy(&mutex_);
        pthread_cond_destroy(&cond_);
    }

private:
    std::vector<PthreadData> tds_;//线程数量
    std::queue<T> rq_;//任务数量
    pthread_mutex_t mutex_;
    pthread_cond_t cond_;
};